package com.sks.web.action.house;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.stereotype.Controller;

import com.sks.bean.pojo.Message;
import com.sks.bean.pojo.Users;
import com.sks.service.house.MessageService;
import com.sks.utils.WebUtil;
import com.sks.web.action.BasicAction;
import com.sks.web.formbean.house.MessageForm;

@Controller("/sks/message")
public class UserMessageAction extends BasicAction {
	@Resource(name = "messageServiceBean") private MessageService service;
	
	public ActionForward addUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	 	//this.saveToken(request);
		Long count = service.countByIpAndDate(this.getRemoteAddr(request), new Date());
		request.setAttribute("messageCount", null == count ? 0 : count);
		return mapping.findForward(ADDUI);
	}
	
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String result ="success";
		String msgText ="";
		
		
		Message msg = new Message();
		MessageForm formbean = (MessageForm) form;
		formbean.copyToObj(msg);
		
		String randCode = (String) request.getSession().getAttribute("randCode");
		request.getSession().setAttribute("randCode",null);
		
		if(!randCode.equalsIgnoreCase(formbean.getRandCode())){
				result ="failed";
				msgText = "验证码错误，请重新输入";
				 
		}else{
			//判断用户是否登录过
			Users user= WebUtil.getUsers(request); 
			if(null != user){
				msg.setUserId(user.getUserId());
			}
			msg.setCreateTime(new Date());
			msg.setIpAddress(this.getRemoteAddr(request));
			msg.setRead(false);
			
			try{
				service.save(msg);
			}catch(Exception e){
				result ="failed";
			}
		}
		response.setContentType("text/xml;charset=UTF-8");
		response.getWriter().print("{'result':'"+ result +"','message':'" + msgText + "'}");
		return null;
	}
	@Override
	protected ActionForward validateToken(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response, String methodName) throws Exception {
		return null;
	}
}
